// 全局变量
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
let cart = JSON.parse(localStorage.getItem('cart')) || [];
let users = JSON.parse(localStorage.getItem('users')) || [];
let regions = []; // 用于存储省市区数据

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!currentUser) {
        localStorage.setItem('redirectAfterLogin', 'profile.html');
        window.location.href = 'login.html';
        return;
    }
    
    // 更新购物车数量
    updateCartCount();
    
    // 设置登录状态
    updateLoginStatus();
    
    // 加载用户数据
    loadUserData();
    
    // 加载订单数据
    loadOrders();
    
    // 加载地址数据
    loadAddresses();
    
    // 加载省市区数据
    loadRegions();
    
    // 标签页切换
    document.querySelectorAll('.profile-menu a[data-tab]').forEach(tab => {
        tab.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 更新活动标签
            document.querySelectorAll('.profile-menu a').forEach(item => {
                item.classList.remove('active');
            });
            this.classList.add('active');
            
            // 显示对应内容
            const tabId = this.getAttribute('data-tab') + '-tab';
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.getElementById(tabId).classList.add('active');
            
            // 如果是订单标签页，重新加载订单
            if (tabId === 'orders-tab') {
                loadOrders();
            }
        });
    });
    
    // 检查URL中的标签参数
    const urlHash = window.location.hash;
    if (urlHash) {
        const tabLink = document.querySelector(`.profile-menu a[href="${urlHash}"]`);
        if (tabLink) {
            tabLink.click();
        }
    }
    
    // 个人资料表单提交
    document.getElementById('profile-form').addEventListener('submit', function(e) {
        e.preventDefault();
        saveProfile();
    });
    
    // 订单筛选按钮
    document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            loadOrders(this.getAttribute('data-status'));
        });
    });
    
    // 添加地址按钮
    document.getElementById('add-address-btn').addEventListener('click', function() {
        document.getElementById('address-form-container').style.display = 'block';
        this.style.display = 'none';
        resetAddressForm();
    });
    
    // 取消添加地址
    document.getElementById('cancel-address-btn').addEventListener('click', function() {
        document.getElementById('address-form-container').style.display = 'none';
        document.getElementById('add-address-btn').style.display = 'block';
    });
    
    // 地址表单提交
    document.getElementById('address-form').addEventListener('submit', function(e) {
        e.preventDefault();
        saveAddress();
    });
    
    // 修改密码按钮
    document.getElementById('change-password-btn').addEventListener('click', function() {
        document.getElementById('password-form-container').style.display = 'block';
        this.style.display = 'none';
    });
    
    // 取消修改密码
    document.getElementById('cancel-password-btn').addEventListener('click', function() {
        document.getElementById('password-form-container').style.display = 'none';
        document.getElementById('change-password-btn').style.display = 'block';
        document.getElementById('password-form').reset();
    });
    
    // 密码表单提交
    document.getElementById('password-form').addEventListener('submit', function(e) {
        e.preventDefault();
        changePassword();
    });
    
    // 登出按钮
    document.getElementById('logout-btn').addEventListener('click', function(e) {
        e.preventDefault();
        logout();
    });
});

// 加载用户数据
function loadUserData() {
    // 更新用户信息显示
    document.getElementById('username').textContent = currentUser.name || '用户';
    document.getElementById('member-since').textContent = `会员日期: ${formatDate(currentUser.registeredAt)}`;
    
    // 更新头像
    const avatarName = currentUser.name || '用户';
    document.getElementById('user-avatar').src = `https://ui-avatars.com/api/?name=${encodeURIComponent(avatarName)}&background=3498db&color=fff`;
    
    // 填充个人资料表单
    document.getElementById('profile-name').value = currentUser.name || '';
    document.getElementById('profile-email').value = currentUser.email || '';
    document.getElementById('profile-phone').value = currentUser.phone || '';
    
    if (currentUser.birthday) {
        document.getElementById('profile-birthday').value = currentUser.birthday.split('T')[0];
    }
    
    if (currentUser.gender) {
        document.getElementById('profile-gender').value = currentUser.gender;
    }
}

// 保存个人资料
function saveProfile() {
    // 获取表单数据
    const name = document.getElementById('profile-name').value;
    const phone = document.getElementById('profile-phone').value;
    const birthday = document.getElementById('profile-birthday').value;
    const gender = document.getElementById('profile-gender').value;
    
    // 更新当前用户数据
    currentUser.name = name;
    currentUser.phone = phone;
    if (birthday) {
        currentUser.birthday = new Date(birthday).toISOString();
    }
    currentUser.gender = gender;
    
    // 更新本地存储
    localStorage.setItem('currentUser', JSON.stringify(currentUser));
    
    // 更新用户列表中的用户数据
    const userIndex = users.findIndex(u => u.id === currentUser.id);
    if (userIndex !== -1) {
        users[userIndex] = currentUser;
        localStorage.setItem('users', JSON.stringify(users));
    }
    
    // 更新显示
    loadUserData();
    
    showAlert('个人资料已更新', 'success');
}

// 加载订单数据
function loadOrders(filter = 'all') {
    const ordersList = document.getElementById('orders-list');
    ordersList.innerHTML = '<div class="loading">加载中...</div>';
    
    // 模拟API请求延迟
    setTimeout(() => {
        const allOrders = JSON.parse(localStorage.getItem('orders')) || [];
        const userOrders = allOrders.filter(order => order.userId === currentUser.id || order.email === currentUser.email);
        
        if (userOrders.length === 0) {
            ordersList.innerHTML = `
                <div class="empty-orders">
                    <p>您还没有任何订单</p>
                    <a href="index.html" class="btn">去购物</a>
                </div>
            `;
            return;
        }
        
        // 应用筛选
        let filteredOrders = userOrders;
        if (filter !== 'all') {
            filteredOrders = userOrders.filter(order => order.status === filter);
        }
        
        // 按日期降序排序
        filteredOrders.sort((a, b) => new Date(b.date) - new Date(a.date));
        
        // 显示订单
        ordersList.innerHTML = '';
        filteredOrders.forEach(order => {
            const orderElement = document.createElement('div');
            orderElement.className = 'order-card';
            orderElement.innerHTML = `
                <div class="order-header">
                    <div class="order-id">订单号: ${order.id}</div>
                    <div class="order-date">${formatDate(order.date)}</div>
                    <div class="order-status ${order.status}">${getOrderStatusText(order.status)}</div>
                    <div class="order-total">$${order.total.toFixed(2)}</div>
                </div>
                <div class="order-details">
                    <div class="order-items-preview">
                        ${order.items.slice(0, 3).map(item => `
                            <div class="order-item-preview">
                                <img src="${item.image}" alt="${item.name}">
                                <span>${item.name} ×${item.quantity}</span>
                            </div>
                        `).join('')}
                        ${order.items.length > 3 ? `<div class="more-items">+${order.items.length - 3}更多</div>` : ''}
                    </div>
                    <div class="order-actions">
                        <a href="#" class="view-order-btn" data-order="${order.id}">查看详情</a>
                        ${order.status === 'pending' ? '<a href="#" class="pay-order-btn">立即支付</a>' : ''}
                        ${order.status === 'pending' || order.status === 'processing' ? '<a href="#" class="cancel-order-btn">取消订单</a>' : ''}
                        ${order.status === 'completed' ? '<a href="#" class="review-order-btn">评价商品</a>' : ''}
                    </div>
                </div>
            `;
            ordersList.appendChild(orderElement);
        });
        
        // 添加订单操作事件
        document.querySelectorAll('.view-order-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const orderId = this.getAttribute('data-order');
                viewOrderDetails(orderId);
            });
        });
        
    }, 500);
}

// 查看订单详情
function viewOrderDetails(orderId) {
    const allOrders = JSON.parse(localStorage.getItem('orders')) || [];
    const order = allOrders.find(o => o.id === orderId);
    
    if (!order) {
        showAlert('订单不存在', 'error');
        return;
    }
    
    // 在实际应用中，这里可以跳转到订单详情页或显示模态框
    alert(`查看订单 ${orderId} 的详情\n状态: ${getOrderStatusText(order.status)}\n总金额: $${order.total.toFixed(2)}`);
}

// 加载地址数据
function loadAddresses() {
    const addressList = document.getElementById('address-list');
    
    if (!currentUser.addresses || currentUser.addresses.length === 0) {
        addressList.innerHTML = '<p class="no-address">您还没有添加任何收货地址</p>';
        return;
    }
    
    addressList.innerHTML = '';
    currentUser.addresses.forEach((address, index) => {
        const addressElement = document.createElement('div');
        addressElement.className = `address-card ${address.default ? 'default' : ''}`;
        addressElement.innerHTML = `
            <div class="address-content">
                <h3>${address.name} <span class="phone">${address.phone}</span></h3>
                <p class="address-text">${address.province} ${address.city} ${address.district || ''} ${address.detail}</p>
                ${address.default ? '<span class="default-badge">默认地址</span>' : ''}
            </div>
            <div class="address-actions">
                <button class="edit-address-btn" data-index="${index}">编辑</button>
                <button class="delete-address-btn" data-index="${index}">删除</button>
                ${!address.default ? '<button class="set-default-btn" data-index="${index}">设为默认</button>' : ''}
            </div>
        `;
        addressList.appendChild(addressElement);
    });
    
    // 添加地址操作事件
    document.querySelectorAll('.edit-address-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const index = parseInt(this.getAttribute('data-index'));
            editAddress(index);
        });
    });
    
    document.querySelectorAll('.delete-address-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const index = parseInt(this.getAttribute('data-index'));
            deleteAddress(index);
        });
    });
    
    document.querySelectorAll('.set-default-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const index = parseInt(this.getAttribute('data-index'));
            setDefaultAddress(index);
        });
    });
}

// 加载省市区数据
function loadRegions() {
    // 在实际应用中，这里应该从API获取数据
    // 这里使用简化的中国省市区数据
    regions = [
        {
            name: "北京市",
            cities: [
                {name: "北京市", districts: ["东城区", "西城区", "朝阳区", "海淀区", "丰台区", "石景山区", "通州区"]}
            ]
        },
        {
            name: "上海市",
            cities: [
                {name: "上海市", districts: ["黄浦区", "徐汇区", "长宁区", "静安区", "普陀区", "虹口区", "杨浦区"]}
            ]
        },
        {
            name: "广东省",
            cities: [
                {name: "广州市", districts: ["天河区", "越秀区", "海珠区", "荔湾区", "白云区", "黄埔区"]},
                {name: "深圳市", districts: ["福田区", "罗湖区", "南山区", "盐田区", "宝安区", "龙岗区"]}
            ]
        }
    ];
    
    // 填充省份选择器
    const provinceSelect = document.getElementById('address-province');
    regions.forEach(province => {
        const option = document.createElement('option');
        option.value = province.name;
        option.textContent = province.name;
        provinceSelect.appendChild(option);
    });
    
    // 省份变化时更新城市
    provinceSelect.addEventListener('change', function() {
        const selectedProvince = regions.find(p => p.name === this.value);
        const citySelect = document.getElementById('address-city');
        
        citySelect.innerHTML = '<option value="">选择市</option>';
        citySelect.disabled = !selectedProvince;
        
        if (selectedProvince) {
            selectedProvince.cities.forEach(city => {
                const option = document.createElement('option');
                option.value = city.name;
                option.textContent = city.name;
                citySelect.appendChild(option);
            });
            citySelect.disabled = false;
        }
        
        // 重置区县选择器
        document.getElementById('address-district').innerHTML = '<option value="">选择区/县</option>';
        document.getElementById('address-district').disabled = true;
    });
    
    // 城市变化时更新区县
    document.getElementById('address-city').addEventListener('change', function() {
        const selectedProvince = regions.find(p => p.name === document.getElementById('address-province').value);
        if (!selectedProvince) return;
        
        const selectedCity = selectedProvince.cities.find(c => c.name === this.value);
        const districtSelect = document.getElementById('address-district');
        
        districtSelect.innerHTML = '<option value="">选择区/县</option>';
        districtSelect.disabled = !selectedCity;
        
        if (selectedCity && selectedCity.districts) {
            selectedCity.districts.forEach(district => {
                const option = document.createElement('option');
                option.value = district;
                option.textContent = district;
                districtSelect.appendChild(option);
            });
            districtSelect.disabled = false;
        }
    });
}

// 添加/保存地址
function saveAddress() {
    const name = document.getElementById('address-name').value;
    const phone = document.getElementById('address-phone').value;
    const province = document.getElementById('address-province').value;
    const city = document.getElementById('address-city').value;
    const district = document.getElementById('address-district').value;
    const detail = document.getElementById('address-detail').value;
    const postal = document.getElementById('address-postal').value;
    const isDefault = document.getElementById('address-default').checked;
    
    // 验证必填字段
    if (!name || !phone || !province || !city || !detail) {
        showAlert('请填写所有必填字段', 'error');
        return;
    }
    
    // 创建新地址对象
    const newAddress = {
        name,
        phone,
        province,
        city,
        detail,
        postal,
        default: isDefault
    };
    
    if (district) {
        newAddress.district = district;
    }
    
    // 如果是默认地址，先取消其他默认地址
    if (isDefault) {
        if (currentUser.addresses) {
            currentUser.addresses.forEach(addr => addr.default = false);
        }
    }
    
    // 初始化地址数组
    if (!currentUser.addresses) {
        currentUser.addresses = [];
    }
    
    // 检查是否在编辑现有地址
    const editingIndex = document.getElementById('address-form').getAttribute('data-editing');
    if (editingIndex !== null) {
        // 更新现有地址
        currentUser.addresses[parseInt(editingIndex)] = newAddress;
    } else {
        // 添加新地址
        currentUser.addresses.push(newAddress);
    }
    
    // 如果没有默认地址，将第一个地址设为默认
    if (currentUser.addresses.length === 1) {
        currentUser.addresses[0].default = true;
    }
    
    // 更新本地存储
    localStorage.setItem('currentUser', JSON.stringify(currentUser));
    
    // 更新用户列表
    const userIndex = users.findIndex(u => u.id === currentUser.id);
    if (userIndex !== -1) {
        users[userIndex] = currentUser;
        localStorage.setItem('users', JSON.stringify(users));
    }
    
    // 重新加载地址列表
    loadAddresses();
    
    // 重置表单
    document.getElementById('address-form-container').style.display = 'none';
    document.getElementById('add-address-btn').style.display = 'block';
    document.getElementById('address-form').removeAttribute('data-editing');
    
    showAlert('地址已保存', 'success');
}

// 编辑地址
function editAddress(index) {
    const address = currentUser.addresses[index];
    
    // 填充表单
    document.getElementById('address-name').value = address.name;
    document.getElementById('address-phone').value = address.phone;
    document.getElementById('address-detail').value = address.detail;
    document.getElementById('address-postal').value = address.postal || '';
    document.getElementById('address-default').checked = address.default || false;
    
    // 设置表单正在编辑的地址索引
    document.getElementById('address-form').setAttribute('data-editing', index);
    
    // 显示表单
    document.getElementById('address-form-container').style.display = 'block';
    document.getElementById('add-address-btn').style.display = 'none';
}

// 删除地址
function deleteAddress(index) {
    if (!confirm('确定要删除这个地址吗？')) return;
    
    currentUser.addresses.splice(index, 1);
    
    // 如果删除了默认地址且还有其他地址，将第一个地址设为默认
    if (currentUser.addresses.length > 0 && !currentUser.addresses.some(addr => addr.default)) {
        currentUser.addresses[0].default = true;
    }
    
    // 更新本地存储
    localStorage.setItem('currentUser', JSON.stringify(currentUser));
    
    // 更新用户列表
    const userIndex = users.findIndex(u => u.id === currentUser.id);
    if (userIndex !== -1) {
        users[userIndex] = currentUser;
        localStorage.setItem('users', JSON.stringify(users));
    }
    
    // 重新加载地址列表
    loadAddresses();
    
    showAlert('地址已删除', 'success');
}

// 设为默认地址
function setDefaultAddress(index) {
    currentUser.addresses.forEach(addr => addr.default = false);
    currentUser.addresses[index].default = true;
    
    // 更新本地存储
    localStorage.setItem('currentUser', JSON.stringify(currentUser));
    
    // 更新用户列表
    const userIndex = users.findIndex(u => u.id === currentUser.id);
    if (userIndex !== -1) {
        users[userIndex] = currentUser;
        localStorage.setItem('users', JSON.stringify(users));
    }
    
    // 重新加载地址列表
    loadAddresses();
}

// 重置地址表单
function resetAddressForm() {
    document.getElementById('address-form').reset();
    document.getElementById('address-province').value = '';
    document.getElementById('address-city').innerHTML = '<option value="">选择市</option>';
    document.getElementById('address-city').disabled = true;
    document.getElementById('address-district').innerHTML = '<option value="">选择区/县</option>';
    document.getElementById('address-district').disabled = true;
    document.getElementById('address-form').removeAttribute('data-editing');
}

// 修改密码
function changePassword() {
    const currentPassword = document.getElementById('current-password').value;
    const newPassword = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    
    // 验证当前密码
    if (currentPassword !== currentUser.password) {
        showAlert('当前密码不正确', 'error');
        return;
    }
    
    // 验证新密码
    if (newPassword.length < 6) {
        showAlert('新密码长度不能少于6位', 'error');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        showAlert('两次输入的新密码不一致', 'error');
        return;
    }
    
    // 更新密码
    currentUser.password = newPassword;
    
    // 更新本地存储
    localStorage.setItem('currentUser', JSON.stringify(currentUser));
    
    // 更新用户列表
    const userIndex = users.findIndex(u => u.id === currentUser.id);
    if (userIndex !== -1) {
        users[userIndex] = currentUser;
        localStorage.setItem('users', JSON.stringify(users));
    }
    
    // 重置表单
    document.getElementById('password-form').reset();
    document.getElementById('password-form-container').style.display = 'none';
    document.getElementById('change-password-btn').style.display = 'block';
    
    showAlert('密码已更新', 'success');
}

// 登出
function logout() {
    currentUser = null;
    localStorage.removeItem('currentUser');
    updateLoginStatus();
    window.location.href = 'index.html';
}

// 更新购物车数量显示
function updateCartCount() {
    const count = cart.reduce((total, item) => total + item.quantity, 0);
    const cartCountElement = document.getElementById('cart-count');
    if (cartCountElement) {
        cartCountElement.textContent = count;
    }
}

// 更新登录状态
function updateLoginStatus() {
    const loginLink = document.getElementById('login-link');
    const profileLink = document.querySelector('nav ul li a[href="profile.html"]');
    
    if (!loginLink) return;
    
    if (currentUser) {
        loginLink.textContent = '登出';
        loginLink.href = '#';
        loginLink.addEventListener('click', logout);
        if (profileLink) profileLink.style.display = 'block';
    } else {
        loginLink.textContent = '登录';
        loginLink.href = '#';
        loginLink.addEventListener('click', function(e) {
            e.preventDefault();
            localStorage.setItem('redirectAfterLogin', window.location.pathname);
            window.location.href = 'login.html';
        });
        if (profileLink) profileLink.style.display = 'none';
    }
}

// 辅助函数：格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
}

// 辅助函数：获取订单状态文本
function getOrderStatusText(status) {
    const statusMap = {
        'pending': '待付款',
        'processing': '处理中',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 显示提示信息
function showAlert(message, type) {
    // 移除现有的提示
    const existingAlert = document.querySelector('.alert');
    if (existingAlert) {
        existingAlert.remove();
    }
    
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type}`;
    alertDiv.textContent = message;
    
    const container = document.querySelector('.profile-content');
    if (container) {
        container.insertBefore(alertDiv, container.firstChild);
    } else {
        document.body.insertBefore(alertDiv, document.body.firstChild);
    }
    
    // 5秒后自动消失
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}